/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kimstore.gui.staff;

import com.kimstore.bean.Batch;
import com.kimstore.bean.Item;
import com.kimstore.bean.Order;
import com.kimstore.bean.Staff;
import com.kimstore.factory.DaoFactory;
import com.kimstore.gui.main.Inventory;
import com.kimstore.main.controller.StaffTabController;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Administrator
 */
public class ViewStaffController {

    private StaffTabController parentController;
    private ViewStaffWindow window;
    private Staff staff;

    public ViewStaffController(StaffTabController parentController, int staffId) {
        this.parentController = parentController;
        this.staff = DaoFactory.getInstance().getStaffDao().findById(staffId);
    }

    public void displayWindow() {
        this.window = new ViewStaffWindow(this);

        List<Order> orders = DaoFactory.getInstance().getOrderDao().findByStaff(staff);
        List<Batch> batches = DaoFactory.getInstance().getBatchDao().findByStaff(staff);
        this.window.populateWindow(staff, getInItems(batches), getOutItems(orders));
        this.window.showWindow();
    }

    public void fromWindow(String staffName) {
        staff.setName(staffName);

        DaoFactory.getInstance().getStaffDao().saveOrUpdate(staff);
        parentController.refreshTable();
    }

    private List<Item> getInItems(List<Batch> batches) {
        List<Item> list = new ArrayList<Item>();

        for (Batch b : batches) {
            for (Item i : b.getItems()) {
                i.setInDate(b.getDateReceived());
                list.add(i);
            }
        }

        return list;
    }

    private List<Item> getOutItems(List<Order> orders) {
        List<Item> list = new ArrayList<Item>();

        for (Order o : orders) {
            for (Item i : o.getItems()) {
                i.setOutDate(o.getOrderDate());

                list.add(i);
            }
        }

        return list;
    }

    public void createManageCredentialsController() {
        ManageCredentialsController controller = new ManageCredentialsController(this, staff);
        controller.displayWindow();
    }

    public void createManageCredentialsControllerCallback() {
    }

    public void validate(String name) {
        if (name.isEmpty() || name == null) {
            throw new Error("<html><b>Staff name</b> has not been filled up");
        }

        boolean exists = DaoFactory.getInstance().getStaffDao().existsName(name);

        if (exists) {
            throw new Error("<html><b>Staff name</b> has already been taken.</html>");
        }
    }
}
